//
//  WatchWCSessionManager.m
//  WatchApp Extension
//
//  Created by kiveen on 2019/5/23.
//  Copyright © 2019 wsl. All rights reserved.
//

#import "WatchWCSessionManager.h"

@interface WatchWCSessionManager() <WCSessionDelegate>

@end

static WatchWCSessionManager *manager = nil;

@implementation WatchWCSessionManager 

+ (instancetype)sharedInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
    });
    return manager;
    
}
+ (id)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [super allocWithZone:zone];
    });
    return manager;
}

// MARK: lazyload
- (WCSession *)session{
    if (!_session) {
        _session = [WCSession defaultSession];
    }
    return _session;
}

// 2.激活session
- (void)startSession{
    self.session.delegate = self;
    [self.session activateSession];
}

/** Called when the session has completed activation. If session state is WCSessionActivationStateNotActivated there will be an error with more details. */
- (void)session:(WCSession *)session activationDidCompleteWithState:(WCSessionActivationState)activationState error:(nullable NSError *)error{
    NSLog(@"Watch-activationDidCompleteWithState");
}

// MARK: sendMsgToPhone
- (void)sendMsgToPhone:(NSDictionary *)msg {
    if (self.session.isReachable){
        [self.session sendMessage:msg replyHandler:^(NSDictionary<NSString *,id> * _Nonnull replyMessage) {
            NSLog(@"replyMessage:%@",replyMessage);
            
        } errorHandler:^(NSError * _Nonnull error) {
            NSLog(@"replyMessageError:%@", error.description);
            
        }];
    }else{
        NSLog(@"sendError:%@", @"请先开启此应用Apple客户端");
    }
    
}

// MARK: apple watch 收到消息并回复
- (void)session:(WCSession *)session didReceiveMessage:(nonnull NSDictionary<NSString *,id> *)message replyHandler:(nonnull void (^)(NSDictionary<NSString *,id> * _Nonnull))replyHandler{
    NSLog(@"didReceiveMessage=%@", message);
    if (_delegate && [_delegate respondsToSelector:@selector(receiveMessage:replyHandler:)]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.delegate receiveMessage:message replyHandler:replyHandler];
        });
    }
}

@end
